package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import acoes.AcaoFactory;
import acoes.interfaces.Acao;

@WebServlet(description = "Servlet de entrada no sistema", urlPatterns = { "/entrada" })
public class Entrada extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public Entrada() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}
	
	private static void tratarRequisicao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nomeAcao = request.getParameter("acao");
		
		if (nomeAcao == null || nomeAcao.equals("")){
			nomeAcao = "main";
		}
		
		AcaoFactory acaoFactory = AcaoFactory.getInstance();
		Acao acao = acaoFactory.criarAcao(nomeAcao);
		
		try {
			acao.tratarRequisicao(request, response);
		} catch (Exception e){
			request.setAttribute("exception", e);
			
			ServletContext servletContext = request.getServletContext();
			RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/WEB-INF/jsp/erro.jsp");
			dispatcher.forward(request,response);
		}
	}
}
